<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryForm" :inline="true">
      <el-form-item label="分类" prop="asseType">
          <el-select v-model="queryParams.asseType" clearable placeholder="请选择">
            <el-option v-for="item in asseTypeOptions" :label="item.dictLabel" :value="item.dictValue" :key="item.id">
          </el-option>
        </el-select>
      </el-form-item>
      <el-form-item label="资产编号" prop="asseCode">
        <el-input
          v-model="queryParams.asseCode"
          placeholder="请输入资产编号"
          clearable
          size="small"
          style="width: 240px"
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="资产名称" prop="asseName">
        <el-input
          v-model="queryParams.asseName"
          placeholder="请输入资产名称"
          clearable
          size="small"
          style="width: 240px"
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="买入时间">
        <el-date-picker
                v-model="dateRange"
                size="small"
                style="width: 240px"
                value-format="yyyy-MM-dd"
                type="daterange"
                range-separator="-"
                start-placeholder="开始日期"
                end-placeholder="结束日期"
        />
      </el-form-item>
      <!-- <el-form-item label="负责人" prop="assePersonName">
        <el-input
          v-model="queryParams.assePersonName"
          placeholder="请输入负责人名称"
          clearable
          size="small"
          style="width: 240px"
          @keyup.enter.native="handleQuery"
        />
      </el-form-item> -->
      <!-- <el-form-item label="状态" prop="asseStatus">
          <el-select v-model="queryParams.asseStatus" clearable placeholder="请选择">
            <el-option v-for="item in statusOptions" :label="item.dictLabel" :value="item.dictValue" :key="item.id">
          </el-option>
        </el-select>
      </el-form-item> -->
      <el-form-item>
        <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
        <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button
          type="primary"
          icon="el-icon-plus"
          size="mini"
          @click="handleAdd"
        >新增</el-button>
      </el-col>
      <!-- <el-col :span="1.5">
        <el-button
          type="success"
          icon="el-icon-edit"
          size="mini"
          :disabled="single"
          @click="handleUpdate"
        >修改</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="danger"
          icon="el-icon-delete"
          size="mini"
          :disabled="multiple"
          @click="handleDelete"
        >删除</el-button>
      </el-col> -->
      <!-- <el-col :span="1.5">
        <el-button
          type="warning"
          icon="el-icon-download"
          size="mini"
          @click="handleExport"
          v-hasPermi="['system:post:export']"
        >导出</el-button>
      </el-col> -->
    </el-row>

    <el-table v-loading="loading" :data="assetsList"  @selection-change="handleSelectionChange">
      <!-- <el-table-column type="selection" width="55" align="center" /> -->
      <!-- <el-table-column label="序号" type="index" width="50" /> -->
      <el-table-column label="资产编号" prop="asseCode"  />
      <el-table-column label="资产名称" prop="asseName"  :show-overflow-tooltip="true"  />
      <el-table-column label="资产分类" prop="asseType"  :show-overflow-tooltip="true"  >
       <template slot-scope="scope">
        {{
          asseTypeOptions.filter(function (item, index, arr) {
          return item.dictValue == scope.row.asseType
          })[0].dictLabel
          }}
       </template>
      </el-table-column>
      <!-- <el-table-column label="买入时间" prop="asseBuyTime" :show-overflow-tooltip="true" >
        <template slot-scope="scope">
          <span>{{ parseTime(scope.row.asseBuyTime) }}</span>
        </template>
      </el-table-column> -->
      <!-- <el-table-column label="买入价格" prop="asseBuyPrice" :show-overflow-tooltip="true" /> -->
      <!-- <el-table-column label="当前价格" prop="asseCurrentPrice" :show-overflow-tooltip="true" /> -->
      <!-- <el-table-column label="负责人" prop="assePersonName"  :show-overflow-tooltip="true"  /> -->
      <!-- <el-table-column label="状态" align="center" prop="asseStatus" :show-overflow-tooltip="true" >
        <template slot-scope="scope">
          {{
          statusOptions.filter(function (item, index, arr) {
          return item.dictValue == scope.row.asseStatus
          })[0].dictLabel
          }}
        </template>
      </el-table-column> -->
      <el-table-column label="库存数量"  prop="asseCount" :show-overflow-tooltip="true" ></el-table-column>
      <el-table-column label="创建时间"  :show-overflow-tooltip="true" prop="createTime">
        <template slot-scope="scope">
          <span>{{ parseTime(scope.row.createTime) }}</span>
        </template>
      </el-table-column>
      <el-table-column label="操作" align="center" :show-overflow-tooltip="true">
        <template slot-scope="scope">
          <el-button
                  size="mini"
                  circle type="success"
                  icon="el-icon-edit"
                  @click="handleUpdate(scope.row)"
          />
          <el-button
                  size="mini"
                  circle type="danger"
                  icon="el-icon-delete"
                  @click="handleDelete(scope.row)"
          />
        </template>
      </el-table-column>
    </el-table>

    <pagination
      v-show="total>0"
      :total="total"
      :page.sync="queryParams.pageNum"
      :limit.sync="queryParams.pageSize"
      @pagination="getList"
    />

    <!-- 添加或修改角色配置对话框 -->
    <el-dialog :title="title" :visible.sync="open" width="500px">
      <el-form ref="form" :model="form" :rules="rules" label-width="80px">
        <el-form-item label="资产编码" prop="asseCode">
          <el-input v-model="form.asseCode" placeholder="请输入资产编号" />
        </el-form-item>
        <el-form-item label="资产名称" prop="asseName">
          <el-input v-model="form.asseName" placeholder="请输入资产名称" />
        </el-form-item>
        <el-form-item label="分类" prop="asseType">
          <el-select v-model="form.asseType" clearable placeholder="请选择" style="width:100%">
            <el-option v-for="item in asseTypeOptions" :label="item.dictLabel" :value="item.dictValue" :key="item.id">
          </el-option>
        </el-select>
        </el-form-item>
        <!-- <el-form-item label="买入时间" prop="asseBuyTime">
          <el-date-picker style="width:100%"
                  v-model="form.asseBuyTime"
                  type="datetime"
                  placeholder="选择日期时间">
                </el-date-picker>
        </el-form-item> -->
        <!-- <el-form-item label="买入价格" prop="asseBuyPrice">
          <el-input v-model="form.asseBuyPrice" controls-position="right" :min="0" />
        </el-form-item> -->
        <!-- <el-form-item label="当前价格" prop="asseCurrentPrice">
          <el-input v-model="form.asseCurrentPrice" controls-position="right" :min="0" />
        </el-form-item> -->
        <!-- <el-form-item label="负责人" prop="ccUserList" v-show="!isView">
            <input type="hidden" v-model="form.currApprovedBy"/>
            <el-tag v-for="item in ccUserList" :key="item.id" style="margin-left: 3px;">{{item.userName}}</el-tag>
            <el-button type="info" plain size="mini"  icon="el-icon-plus" @click="handleUser">选择人员</el-button>
            <el-button type="info" plain size="mini" icon="el-icon-delete" @click="clearUser" v-if="ccUserList.length>0">清空人员</el-button>
        </el-form-item> -->
        <!-- <el-form-item label="状态" prop="asseStatus">
          <el-radio-group v-model="form.asseStatus">
            <el-radio
              v-for="dict in statusOptions"
              :key="dict.dictValue"
              :label="dict.dictValue"
            >{{dict.dictLabel}}</el-radio>
          </el-radio-group>
        </el-form-item> -->
        <el-form-item label="库存数量" v-if="form.id==null" prop="asseCount" >
          <el-input type="input"  v-model="form.asseCount" placeholder="请输入库存数量" />
        </el-form-item>
        <el-form-item label="备注">
          <el-input v-model="form.remark" type="textarea" placeholder="请输入内容"/>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitForm">确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>

    <el-dialog :visible.sync="dialogVisibleUser" title="选择人员">
      <deptUser @getTaskUser="getCCuser" :multiple="false" v-if="dialogVisibleUser"></deptUser>
    </el-dialog>

  </div>
</template>

<script>
import { listAssets, getAssets, delAssets, addOrUpdateAssets, exportAssets, dataScope, changeAssetsStatus } from "@/api/logistics/assets";
import deptUser from "../../../components/userSelect/deptUser.vue"

export default {
   // import引入的组件需要注入到对象中才能使用
 components: {deptUser},

  data() {
    return {
      // 遮罩层
      loading: true,
      dialogVisibleUser:false,
      isView:false,
      ccUserList:[],
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 总条数
      total: 0,
      // 角色表格数据
      assetsList: [],
      // 弹出层标题
      title: "",
      // 是否显示弹出层
      open: false,
      // 是否显示弹出层（数据权限）
      openDataScope: false,
      // 日期范围
      dateRange: [],
      // 状态数据字典
      statusOptions: [],
      asseTypeOptions: [],
      // 数据范围选项
      dataScopeOptions: [
        {
          value: "1",
          label: "全部数据权限"
        },
        {
          value: "2",
          label: "自定数据权限"
        },
        {
          value: "3",
          label: "本部门数据权限"
        }
      ],
      // 菜单列表
      menuOptions: [],
      // 部门列表
      deptOptions: [],
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        name: undefined,
        AssetsKey: undefined,
        status: undefined
      },
      // 表单参数
      form: {},
      defaultProps: {
        children: "children",
        label: "label"
      },
      // 表单校验
      rules: {
        asseCode: [
          { required: true, message: "资产编码不能为空", trigger: "blur" }
        ],
        asseName: [
          { required: true, message: "资产编码不能为空", trigger: "blur" }
        ],
        asseType: [
          { required: true, message: "资产类别不能空", trigger: "blur" }
        ],
        asseBuyPrice: [
          { required: true, message: "买入价格不能为空", trigger: "blur" }
        ],
        asseStatus: [
          { required: true, message: "状态为必选", trigger: "blur" }
        ]
      }
    };
  },
  created() {
    this.getDicts("asse_status").then(response => {
      this.statusOptions = response.data;
    });
    this.getDicts("asse_type").then(response => {
      this.asseTypeOptions = response.data;
    });
    this.getList();
  },
  methods: {
    handleUser() {
      this.dialogVisibleUser = true
    },
    clearUser() {
      this.ccUserList=[]
      this.form.currApprovedBy=null
    },
    getCCuser(data,isClose){
      this.ccUserList = data
      if(data){
        let ccUser = []
        for(let i=0;i<data.length;i++){
          ccUser.push(data[i].userName)
        }
        this.form.currApprovedBy = ccUser.join(',')
      }
      this.$refs['form'].clearValidate('ccUserList')
      this.dialogVisibleUser = isClose
    },
    /** 查询角色列表 */
    getList() {
      this.loading = true;
      listAssets(this.addDateRange(this.queryParams, this.dateRange,true)).then(
        response => {
          this.assetsList = response.data.list;
          this.total = response.data.total;
          this.loading = false;
        }
      );
    },
    // 角色状态修改
    handleStatusChange(row) {
      let text = row.status === "0" ?  "停用":"启用" ;
      this.$confirm('确认要"' + text + '""' + row.name + '"角色吗?', "警告", {
          confirmButtonText: "确定",
          cancelButtonText: "取消",
          type: "warning"
        }).then(function() {
          return changeAssetsStatus(row.id, row.status);
        }).then(() => {
          this.msgSuccess(text + "成功");
        }).catch(function() {
          row.status = row.status === "0" ? "1" : "0";
        });
    },
    // 取消按钮
    cancel() {
      this.open = false;
      this.reset();
    },
    // 取消按钮（数据权限）
    cancelDataScope() {
      this.openDataScope = false;
      this.reset();
    },
    // 表单重置
    reset() {
      if (this.$refs.menu !== undefined) {
        this.$refs.menu.setCheckedKeys([]);
      }
      this.form = {
        AssetsId: undefined,
        name: undefined,
        AssetsKey: undefined,
        sort: 0,
        status: "0",
        menuIds: [],
        deptIds: [],
        remark: undefined
      };
      this.resetForm("form");
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1;
      this.getList();
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.dateRange = [];
      this.resetForm("queryForm");
      this.handleQuery();
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map(item => item.id)
      this.single = selection.length!==1
      this.multiple = !selection.length
    },
    /** 新增按钮操作 */
    handleAdd() {
      this.ccUserList = [];
      this.reset();
      // this.getMenuTreeselect();
      this.open = true;
      this.title = "添加资产";
    },
    /** 修改按钮操作 */
    handleUpdate(row) {
      this.reset();
      const assetsId = row.id
      console.log("handleUpdate", row)
      getAssets(assetsId).then(response => {
        this.form = response.data;
        this.open = true;
        this.title = "修改资产";
        this.ccUserList = [];
        this.ccUserList[0] = {
          id: this.form.assePerson,
          userName: this.form.assePersonName
        };
      });
    },
    /** 分配数据权限操作 */
    handleDataScope(row) {
      this.reset();
      this.$nextTick(() => {
        this.getAssetsDeptTreeselect(row.id);
      });
      getAssets(row.id).then(response => {
        this.form = response.data;
        this.openDataScope = true;
        this.title = "分配数据权限";
      });
    },
    /** 提交按钮 */
    submitForm: function() {
      this.$refs["form"].validate(valid => {
        if (valid) {
          if (this.form.id !== undefined) {
            this.form.assePerson=this.ccUserList[0].id;
            addOrUpdateAssets(this.form).then(response => {
              if (response.code === 200) {
                this.msgSuccess("修改成功");
                this.open = false;
                this.getList();
              } else {
                this.msgError(response.message);
              }
            });
          } else {
            addOrUpdateAssets(this.form).then(response => {
              if (response.code === 200) {
                this.msgSuccess("新增成功");
                this.open = false;
                this.getList();
              } else {
                this.msgError(response.message);
              }
            });
          }
        }
      });
    },
    /** 提交按钮（数据权限） */
    submitDataScope: function() {
      if (this.form.id !== undefined) {
        this.form.deptIds = this.getDeptAllCheckedKeys();
        dataScope(this.form.id,this.form).then(response => {
          if (response.code === 200) {
            this.msgSuccess("修改成功");
            this.openDataScope = false;
            this.getList();
          } else {
            this.msgError(response.message);
          }
        });
      }
    },
    handleDelete(row){
      this.$confirm('确认要删除吗?', "警告", {
              confirmButtonText: "确定",
              cancelButtonText: "取消",
              type: "warning",
          }).then(()=>{
            delAssets([row.id]).then(resp=>{
                  this.msgSuccess("删除成功");
                  this.getList();
              })
          })
      
    },
    batchDelete(){
      const row = this.rowList
      let ids=[]
      for(let i=0;i<row.length;i++){
          ids[i] = row[i].id
      }
      this.$confirm('确认要删除吗?', "警告", {
              confirmButtonText: "确定",
              cancelButtonText: "取消",
              type: "warning",
          }).then(()=>{
              deleteByIds(ids).then(resp=>{
                  this.msgSuccess("删除成功");
                  this.getList();
              })
          })
    },
    /** 导出按钮操作 */
    handleExport() {
      const queryParams = this.queryParams;
      this.$confirm('是否确认导出所有角色数据项?', "警告", {
          confirmButtonText: "确定",
          cancelButtonText: "取消",
          type: "warning"
        }).then(function() {
          return exportAssets(queryParams);
        }).then(response => {
          this.fileDownload(response.data, "角色管理.xlsx");
        }).catch(function() {});
    }
  }
};
</script>
